<?php 
	/* counter script for the favourites_tabe.php page */

	//start the session
	session_start();

	//gets the url of the selected favourite
	$url = $_GET['url'];
	
	//retrieves the file into an array where each line is a value
	$bookmarks_file = '../bookmarks_data/bookmark_database.txt';
	$bookmark = file($bookmarks_file);
		
	for($i = 0; $i < count($bookmark); $i++)
	{
		//goes through the file line by line
		$temp = explode(' | ', $bookmark[$i]);
			
		//creates an array of the favourites
		$favourite[$i] = array('category' => $temp[0], 'url' => $temp[1], 'name' => $temp[2], 'date' => $temp[3], 'counter' => $temp[4]);
		
		//this if statment looks to see if the url's match and if it does increments the counter by one		
		if ($temp[1] == $url)
		{
			$temp[4] += 1;
			$favourite[$i] = array('category' => $temp[0], 'url' => $temp[1], 'name' => $temp[2], 'date' => $temp[3], 'counter' => $temp[4]);
		}	
	}
	
	//opens the text file
	$fh = fopen($bookmarks_file, "w");
	
	//sets a loop that will rewrite the favourites list
	foreach($favourite as $key => $value)
	{
		//cretes variables of the array values
		$category = trim($value['category']);
		$webAddress = trim($value['url']);
		$pageName = trim($value['name']);
		$date_timestamp = trim($value['date']);
		$visitCounter = trim($value['counter']);
		
		//validates the code so that no blank line is left st the end of the document writing
		if($key == 0)
		{
			//writes the variables to the text file
			fwrite($fh, "$category | $webAddress | $pageName | $date_timestamp | $visitCounter");
		}
		else if($key > 0)
		{
			//writes the variables to the text file
			fwrite($fh, "\r\n$category | $webAddress | $pageName | $date_timestamp | $visitCounter");
		}
	}
	
	//closes the text file
	fclose($fh);
	
	//redirects to link that was clicked on in the table
	header("Location: $url");
?>